package com.koron.common.stub;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.koron.common.bean.*;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.serviceManage.utils.RedisUtils;
import com.koron.util.Constant;
import com.koron.util.HttpUtils;
import com.koron.util.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.swan.bean.MessageBean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class Port {
	private static Logger logger = LoggerFactory.getLogger(Port.class);
	private final String APP_URL = "http://www.ebs.krdev.gdhwater.com/app";
	private final String ORG_URL = "http://www.ebs.krdev.gdhwater.com/org";
	private final String STAFF_URL = "http://www.ebs.krdev.gdhwater.com/staff";
	private final String PERMISSION_URL = "http://www.ebs.krdev.gdhwater.com/permission";
	private final String TARANT_URL = "http://www.ebs.krdev.gdhwater.com/tarant";

	private RedissonClient redisson = SpringContextHolder.getBean(RedissonClient.class);
	/**
	 * 单点登录TOKEN访问 锁前缀KEY
	 */
	private static final String ACCESS_TOKEN_LOCK_KEY = "access_token_lock_";

	// access_token 缓存KEY
	private static final String ACCESS_TOKEN_KEY = "access_token_";

	// redis 锁过期时间
	private static final int ACCESS_TOKEN_LOCK_EX_TIME = 100;



	private SecretBean secret;

	private static final Object o = new Object();

	public Port(String appId, String secret) {
		SecretBean sb = new SecretBean();
		sb.setAppid(appId);
		sb.setSecret(secret);
		this.secret = sb;
	}

	public Port() {
		this(new SecretBean());
	}

	public Port(SecretBean secret) {
		this.secret = secret;
	}

	public MessageBean<AppTarantBean> appinfo2(String appCode, String tarantCode) {
		// 通过httpclient获取数据
		String url = APP_URL + "stub/appinfo2.htm";
		HashMap<String, String> params = new HashMap<>();
		params.put("appCode", appCode);
		params.put("tarantCode", tarantCode);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", AppTarantBean.class);
		}
		MessageBean<AppTarantBean> msg = toBean(data, AppTarantBean.class);
		return msg;
	}

	/**
	 * 获取应用信息
	 */
	public MessageBean<AppTarantBean> appinfo() {
		// 通过httpclient获取数据
		String url = APP_URL + "stub/appinfo.htm";
		HashMap<String, String> params = addCommonParams();
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", AppTarantBean.class);
		}
		MessageBean<AppTarantBean> msg = toBean(data, AppTarantBean.class);
		return msg;
	}

	/**
	 * 获取应用操作信息
	 */
	public MessageBean<List> appOperation() {
		String url = APP_URL + "stub/appoperation.htm";
		HashMap<String, String> params = addCommonParams();
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, OperationBean.class);
		return msg;
	}

	/**
	 * 获取应用角色信息
	 */
	public MessageBean<List> approle() {
		String url = APP_URL + "stub/approle.htm";
		HashMap<String, String> params = addCommonParams();
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, AppRoleBean.class);
		return msg;
	}

	/**
	 * 获取部门结构信息
	 */
	public MessageBean<List> depttree(String orgCode, String deptCode, Integer recursive) {
		String url = ORG_URL + "stub/depttree.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("orgCode", orgCode);
		params.put("deptCode", deptCode);
		if (recursive != null) {
			params.put("recursive", String.valueOf(recursive));
		}
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		// 获取并解析httpclient返回的数据
		MessageBean<List> msg = toList(data, DepartmentTreeBean.class);
		return msg;
	}

	/**
	 * 获取部门职员信息
	 */
	public MessageBean<List> depstaff(String orgCode, String deptCode, Integer recursive) {
		String url = ORG_URL + "stub/depstaff.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("orgCode", orgCode);
		params.put("deptCode", deptCode);
		if (recursive != null) {
			params.put("recursive", String.valueOf(recursive));
		}
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, StaffBean.class);
		return msg;
	}

	/**
	 * token换用户信息
	 */
	public MessageBean<List> getUser(String token) {
		String url = STAFF_URL + "stub/getUser.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("token", token);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, StaffBean.class);
		return msg;
	}

	/**
	 *
	 * @param code
	 * @return
	 */
	public MessageBean<List> staff(String code) {
		return staff(code, null);
	}

	/**
	 * 通过code获取用户信息.
	 *
	 * @param code 用户编码
	 * @param type 类型.1为openid 2为userid null为code
	 */
	public MessageBean<List> staff(String code, Integer type) {

		String url = STAFF_URL + "stub/staff.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("code", code);
		if (type != null) {
			params.put("type", type.toString());
		}
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, StaffBean.class);
		return msg;

	}

	/**
	 * 获取用户所属部门
	 */
	public MessageBean<List> dept(String code) {
		String url = STAFF_URL + "stub/dept.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("code", code);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, DeptBean.class);
		return msg;
	}

	/**
	 * 获取租户信息
	 */
	public MessageBean<TarantBean> tarantinfo() {
		String url = TARANT_URL + "stub/tarantinfo.htm";
		HashMap<String, String> params = addCommonParams();
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", TarantBean.class);
		}
		MessageBean<TarantBean> msg = toBean(data, TarantBean.class);
		return msg;
	}

	/**
	 * 获取租户组织架构列表
	 */
	public MessageBean<List> tarantorg() {
		String url = TARANT_URL + "stub/tarantorg.htm";
		HashMap<String, String> params = addCommonParams();
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, TarantOrgBean.class);
		return msg;
	}

	/**
	 * 角色(群组）移除人员(部门，群组)
	 */
	@SuppressWarnings("unchecked")
	public MessageBean<?> removeRelation(String sourceCode, String[] targetCodes, int type) {
		String url = PERMISSION_URL + "stub/removeRelation.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("sourceCode", sourceCode);
		params.put("type", String.valueOf(type));
		String data = HttpUtils.getData2(params, url, targetCodes, "targetCodes");
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Void.class);
		}
		ObjectMapper mapper = new ObjectMapper();
		MessageBean<Void> msg = null;
		try {
			msg = mapper.readValue(data, MessageBean.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 角色(群组）添加人员(部门，群组)
	 */
	@SuppressWarnings("unchecked")
	public MessageBean<?> addRelation(String sourceCode, String[] targetCodes, int type) {
		String url = PERMISSION_URL + "stub/addRelation.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("sourceCode", sourceCode);
		params.put("type", String.valueOf(type));
		String data = HttpUtils.getData2(params, url, targetCodes, "targetCodes");
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Void.class);
		}
		ObjectMapper mapper = new ObjectMapper();
		MessageBean<Void> msg = null;
		try {
			msg = mapper.readValue(data, MessageBean.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 获取群组（角色）下人员（部门、群组）
	 */
	public MessageBean<Map> queryRelation(String code, int type) {
		String url = PERMISSION_URL + "stub/queryRelation.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("code", code);
		params.put("type", String.valueOf(type));
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Map.class);
		}
		// 将data转换成json
		JsonObject jsonRet = new JsonParser().parse(data).getAsJsonObject();
		int interCode = jsonRet.get("code").getAsInt();
		String description = jsonRet.get("description").getAsString();
		if (interCode != 0)
			return MessageBean.create(interCode, description, Map.class);
		HashMap<String, Object> map = new HashMap<>();
		// 若接口成功的查询到了数据，则将数据转换成实体bean
		JsonArray deptArray = jsonRet.get("data").getAsJsonObject().get("department").getAsJsonArray();
		JsonArray staffArray = jsonRet.get("data").getAsJsonObject().get("staff").getAsJsonArray();
		JsonArray groupArray = jsonRet.get("data").getAsJsonObject().get("group").getAsJsonArray();
		JsonArray operationArray = jsonRet.get("data").getAsJsonObject().get("operation").getAsJsonArray();
		List<DeptBean> deptList = jsonArrayToList(deptArray, DeptBean.class);
		List<StaffBean> staffList = jsonArrayToList(staffArray, StaffBean.class);
		List<GroupBean> groupList = jsonArrayToList(groupArray, GroupBean.class);
		List<OperationBean> operaList = jsonArrayToList(operationArray, OperationBean.class);
		map.put("deptList", deptList);
		map.put("staffList", staffList);
		map.put("groupList", groupList);
		map.put("operaList", operaList);
		MessageBean<Map> msg = MessageBean.create(interCode, description, Map.class);
		msg.setData(map);
		return msg;
	}

	/**
	 * 人员获取角色、群组
	 * @param code
	 * @param type 1024 角色，512 群组， 1024+512：角色+群组
	 * @return
	 */
	public MessageBean<Map> getRolesAndGroupsByStaff(String code, int type) {
		String url = PERMISSION_URL + "stub/getRolesAndGroupsByStaff.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("staffCode", code);
		params.put("type", String.valueOf(type));
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Map.class);
		}
		// 将data转换成json
		JsonObject jsonRet = new JsonParser().parse(data).getAsJsonObject();
		int interCode = jsonRet.get("code").getAsInt();
		String description = jsonRet.get("description").getAsString();
		if (interCode != 0)
			return MessageBean.create(interCode, description, Map.class);
		HashMap<String, Object> map = new HashMap<>();
		// 若接口成功的查询到了数据，则将数据转换成实体bean
		JsonArray roleArray = jsonRet.get("data").getAsJsonObject().get("role").getAsJsonArray();
		JsonArray groupArray = jsonRet.get("data").getAsJsonObject().get("group").getAsJsonArray();
		List<RoleBean> roleList = jsonArrayToList(roleArray, RoleBean.class);
		List<GroupBean> groupList = jsonArrayToList(groupArray, GroupBean.class);
		map.put("role", roleList);
		map.put("group", groupList);
		MessageBean<Map> msg = MessageBean.create(interCode, description, Map.class);
		msg.setData(map);
		return msg;
	}

	/**
	 * 创建群组
	 */
	public MessageBean<?> groupAdd(String name, String attr) {
		String url = PERMISSION_URL + "stub/groupAdd.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("name", name);
		params.put("attr", attr);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Void.class);
		}
		ObjectMapper mapper = new ObjectMapper();
		MessageBean<Void> msg = null;
		try {
			msg = mapper.readValue(data, MessageBean.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 获取操作列表(按照seq升序排列)
	 *
	 * @param seq
	 * @param recursive
	 * @param page
	 * @param pageSize
	 * @param staffcode
	 * @return
	 */
	public MessageBean<Map> getOperations(Long seq, Integer recursive, Integer page, Integer pageSize,
										  String staffcode) {
		String url = PERMISSION_URL + "stub/getOperations.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("seq", String.valueOf(seq));
		params.put("recursive", String.valueOf(recursive));
		params.put("page", String.valueOf(page));
		params.put("pageSize", String.valueOf(pageSize));
		params.put("staffcode", staffcode);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Map.class);
		}
		MessageBean<Map> msg = toMap(data, OperationBean.class);
		return msg;
	}

	/**
	 * 获取操作子节点操作，按seq升序
	 *
	 * @param code      父操作的code
	 * @param recursive 是否包含所有子节点
	 * @param page      页
	 * @param pageSize  页面大小
	 * @param staffcode 职员编码
	 * @return
	 */
	public MessageBean<Map> getOperations(String code, Integer recursive, Integer page, Integer pageSize,
										  String staffcode) {
		String url = PERMISSION_URL + "stub/getOperations.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("code", code);
		params.put("recursive", String.valueOf(recursive));
		params.put("page", String.valueOf(page));
		params.put("pageSize", String.valueOf(pageSize));
		params.put("staffcode", staffcode);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Map.class);
		}
		MessageBean<Map> msg = toMap(data, OperationBean.class);
		return msg;
	}

	/**
	 * 判断是否有操作权限
	 */
	public MessageBean<?> operateTest(String operationCode, String staffCode, String formData) {
		String url = PERMISSION_URL + "stub/operateTest.htm?appid=" + secret.getAppid() + "&secret="
				+ secret.getSecret();
		JSONObject json = new JSONObject();
		json.put("staffCode", staffCode);
		// 将formData 转换成jsonObject
		JSONObject fdata = JSONObject.parseObject(formData);
		json.put("data", fdata);
		// 多个操作数组通过逗号拼接成字符串
		json.put("operationCode", operationCode);
		String body = JSON.toJSONString(json);
		String data = HttpUtils.postData(body, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Void.class);
		}
		ObjectMapper mapper = new ObjectMapper();
		MessageBean<?> msg = null;
		try {
			msg = mapper.readValue(data, MessageBean.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 获取权限范围
	 */
	public MessageBean<?> operateRange(String operationCode, String staffCode) {
		String url = PERMISSION_URL + "stub/operateRange.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("operationCode", operationCode);
		params.put("staffCode", staffCode);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Void.class);
		}
		ObjectMapper mapper = new ObjectMapper();
		MessageBean<?> msg = null;
		try {
			msg = mapper.readValue(data, MessageBean.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 通过ticket获取对应的用户账号
	 * @param ticket
	 * @return
	 */
	public MessageBean<String> getOauth2User(String ticket) {
		MessageBean message = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", String.class);
		if (StringUtils.isBlank(ticket)){
			message.setCode(Constant.MESSAGE_INT_NOMODULE);
			message.setDescription("获取 access_token 信息失败");
			return message;
		}
		String accessToken = "";
		// REDIS 锁的键
		String accessTokenLockKey = ACCESS_TOKEN_LOCK_KEY + ticket;
		// access_token 的缓存key
		String accessTokenKey = ACCESS_TOKEN_KEY + ticket;
		// 获取redis 锁
		RLock orderLock = redisson.getLock(accessTokenLockKey);
		try{
			// 加锁
			orderLock.lock();
			// 设置缓存有效期, 有效期 100S
			RedisUtils.expire(accessTokenLockKey, ACCESS_TOKEN_LOCK_EX_TIME);
			// 获取到 access_token 缓存信息
			accessToken = RedisUtils.get(accessTokenKey);
			if (StringUtils.isEmpty(accessToken)){
				String tokenUrl = ApplicationConfig.getIamTokenUrl().replaceAll("#CODE#", ticket).replaceAll("#SECRET#", ApplicationConfig.getIamSecret());
				String result = com.koron.css2.common.utils.HttpUtils.sendPostForm(tokenUrl, null);
				JSONObject jsonObject = JSONObject.parseObject(result);
				if (jsonObject.containsKey("errcode")){
					message.setCode(Constant.MESSAGE_INT_NOMODULE);
					message.setDescription("获取 access_token 信息失败");
					return message;
				}
				accessToken = jsonObject.getString("access_token");
				int expireIn = jsonObject.getInteger("expires_in");
				RedisUtils.setEx(accessTokenKey, expireIn - 10, accessToken);
			}
			// 为了兼容缓存旧版本中未过期的 access_token 是json串
			if (accessToken.startsWith("{")){
				JSONObject jsonObject = JSONObject.parseObject(accessToken);
				accessToken = jsonObject.getString("access_token");
			}
		}finally {
			//防止报错导致锁得不到释放
			if (orderLock != null && orderLock.isLocked() && orderLock.isHeldByCurrentThread()) {
				orderLock.unlock();
			}
		}
		String getUserUrl = ApplicationConfig.getIamUserUrl().replaceAll("#ACCESS_TOKEN#", accessToken);
		String result = com.koron.css2.common.utils.HttpUtils.sendGetForm( getUserUrl, null);
		logger.info("获取用户信息：{}", result);
		JSONObject jsonObject = JSONObject.parseObject(result);
		// 如果返回的结果信息里包含 errcode 字段，说明获取用户信息出错了
		if (jsonObject.containsKey("errcode")){
			message.setCode(Constant.MESSAGE_INT_NOMODULE);
			message.setDescription("获取用户信息失败");
			return message;
		}
		// 优先取 sprolelist 里的业务系统账号
		if (jsonObject.containsKey("spRoleList")){
			JSONArray jsonArray = jsonObject.getJSONArray("spRoleList");
			if (jsonArray.size() > 0){
				message.setData(jsonArray.getString(0));
			}
		}else {
			// 竹云平台的登录账号
			message.setData(jsonObject.getString("loginName"));
		}
		return message;
	}

	/**
	 * 通过ticket获取对应的用户账号
	 *
	 * @param ticket
	 * @return
	 */
	public MessageBean<String> getStaff(String ticket) {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, String> params = addCommonParams();
		params.put("ticket", ticket);
		params.put("app", secret.getAppid());
		String data = HttpUtils.getData(params, ApplicationConfig.getAppTokenUrl());
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", String.class);
		}
		MessageBean<String> msg = null;
		try {
			msg = mapper.readValue(data, MessageBean.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 获取应用和租户的配置路径
	 */
	public MessageBean<String> getConfigPath(String appCode, String tarantCode) {
		String url = APP_URL + "stub/getConfigPath.htm";
		HashMap<String, String> params = new HashMap<>();
		params.put("appCode", appCode);
		params.put("tarantCode", tarantCode);
		String data = HttpUtils.getData(params, url);
		// 判断是否成功拿到数据
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", String.class);
		}
		ObjectMapper mapper = new ObjectMapper();
		MessageBean<String> msg = null;
		try {
			msg = mapper.readValue(data, MessageBean.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 获取群组列表
	 */
	public MessageBean<Map> getGroups(Integer page, Integer pageSize, String name) {
		String url = PERMISSION_URL + "stub/getGroups.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("page", page.toString());
		params.put("pageSize", pageSize.toString());
		params.put("name", name);
		String data = HttpUtils.getData(params, url);
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", Map.class);
		}
		MessageBean<Map> msg = toMap(data, GroupBean.class);
		return msg;
	}

	/**
	 * 获取角色列表
	 */
	public MessageBean<List> getRoles() {
		String url = PERMISSION_URL + "stub/getRoles.htm";
		HashMap<String, String> params = addCommonParams();
		String data = HttpUtils.getData(params, url);
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, RoleBean.class);
		return msg;
	}

	/**
	 * 当前部门获取上级部门
	 */
	public MessageBean<List> getParentDepts(String orgCode, String deptCode) {
		String url = ORG_URL + "stub/getParentDepts.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("orgCode", orgCode);
		params.put("deptCode", deptCode);
		String data = HttpUtils.getData(params, url);
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, DepartmentTreeBean.class);
		return msg;
	}

	/**
	 * 部门模糊查询
	 */
	public MessageBean<List> DeptFuzzyQuery(String orgCode, String name) {
		String url = ORG_URL + "stub/DeptFuzzyQuery.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("orgCode", orgCode);
		params.put("name", name);
		String data = HttpUtils.getData(params, url);
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, DepartmentTreeBean.class);
		return msg;
	}

	/**
	 * 职员模糊查询
	 */
	public MessageBean<List> getStaffByFuzzy(String orgCode, String name) {
		String url = STAFF_URL + "stub/getStaffByFuzzy.htm";
		HashMap<String, String> params = addCommonParams();
		params.put("orgCode", orgCode);
		params.put("name", name);
		String data = HttpUtils.getData(params, url);
		if ("lose".equals(data)) {
			return MessageBean.create(1000, "http连接异常或者服务未开启", List.class);
		}
		MessageBean<List> msg = toList(data, StaffBean.class);
		return msg;
	}

	// 封装基础的参数
	private HashMap<String, String> addCommonParams() {
		HashMap<String, String> params = new HashMap<>();
		params.put("appid", secret.getAppid());
		params.put("secret", secret.getSecret());
		return params;
	}

	/**
	 *  返回实体bean的接口
	 * @param <T>
	 * @param data
	 * @param clazz
	 * @return
	 */
	private <T> MessageBean<T> toBean(String data, Class<T> clazz) {
		ObjectMapper mapper = new ObjectMapper();

//        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
		// 将data转换成json
		JsonObject jsonRet = new JsonParser().parse(data).getAsJsonObject();
		int code = jsonRet.get("code").getAsInt();
		String description = jsonRet.get("description").getAsString();
		// 判断调用的外部接口是否异常
		if (code != 0)
			return MessageBean.create(code, description, clazz);
		String str = jsonRet.get("data").getAsJsonObject().toString();
		T bean = null;
		try {
			bean = mapper.readValue(str, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		MessageBean<T> msg = MessageBean.create(0, "success", clazz);
		msg.setData(bean);
		return msg;
	}

	/**
	 *  返回list的接口
	 * @param <T>
	 * @param data
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private <T> MessageBean<List> toList(String data, Class<T> clazz) {
		MessageBean<List> msg = MessageBean.create(0, "success", List.class);
		// 将data转换成json
		JsonObject jsonRet = new JsonParser().parse(data).getAsJsonObject();
		int code = jsonRet.get("code").getAsInt();
		String description = jsonRet.get("description").getAsString();
		// 判断调用的外部接口是否异常
		if (code != 0)
			return MessageBean.create(code, description, List.class);
		List<T> list = new ArrayList<>();
		JsonArray array = null;
		try {
			array = jsonRet.getAsJsonArray("data");
		} catch (Exception e) {
			array = jsonRet.get("data").getAsJsonObject().get("list").getAsJsonArray();
		}
		if (array.size() == 0) {
			msg.setData(list);
			return msg;
		}
		// 将数组里面的对象转换为实体bean
		list = jsonArrayToList(array, clazz);
		msg.setData(list);
		return msg;
	}

	/**
	 * 返回map的接口
	 */
	private <T> MessageBean<Map> toMap(String data, Class<T> clazz) {
		MessageBean<Map> msg = MessageBean.create(0, "success", Map.class);
		// 将data转换成json
		JsonObject jsonRet = new JsonParser().parse(data).getAsJsonObject();
		int code = jsonRet.get("code").getAsInt();
		String description = jsonRet.get("description").getAsString();
		// 判断调用的外部接口是否异常
		if (code != 0)
			return MessageBean.create(code, description, Map.class);
		HashMap<String, Object> map = new HashMap<>();
		List<T> list = new ArrayList<>();
		JsonArray array = null;
		try {
			array = jsonRet.get("data").getAsJsonObject().get("list").getAsJsonArray();
			int totalPage = jsonRet.get("data").getAsJsonObject().get("totalPage").getAsInt();
			int totalNumber = jsonRet.get("data").getAsJsonObject().get("totalNumber").getAsInt();
			map.put("totalPage", totalPage);
			map.put("totalNumber", totalNumber);
		} catch (Exception e) {
			e.printStackTrace(); 
		}
		if (array.size() == 0) {
			msg.setData(map);
			return msg;
		}
		// 将数组里面的对象转换为实体bean
		list = jsonArrayToList(array, clazz);
		map.put("list", list);
		msg.setData(map);
		return msg;
	}

	/**
	 *将jsonarray转换成list
	 *
	 * @param <T>
	 */
	private <T> List<T> jsonArrayToList(JsonArray array, Class<T> clazz) {
		List<T> list = new ArrayList<>();
		ObjectMapper mapper = new ObjectMapper();
		if (array != null && array.size() != 0) {
			try {
				for (int i = 0; i < array.size(); i++) {
					String str = array.get(i).getAsJsonObject().toString();
					T bean = mapper.readValue(str, clazz);
					list.add(bean);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}

}
